package com.wf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wf.common.Constants;
import com.wf.common.RoleEnum;
import com.wf.controller.dto.UserDTO;
import com.wf.controller.dto.UserPasswordDTO;
import com.wf.entity.Course;
import com.wf.entity.Menu;
import com.wf.entity.User;
import com.wf.exception.ServiceException; // 自定义异常处理
import com.wf.mapper.RoleMapper;
import com.wf.mapper.RoleMenuMapper;
import com.wf.mapper.UserMapper;
import com.wf.service.IMenuService;
import com.wf.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wf.utils.TokenUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

//     private static final Log LOG = Log.get(); // 控制台日志

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Override
    public UserDTO login(UserDTO userDTO) {
        User one = getUserInfo(userDTO); // 还能查到null 值？
        if (one != null) {
            // 复制属性 把one实例  复制 给实例userDTO
            BeanUtil.copyProperties(one, userDTO, true);  // 忽略大小写
            // 设置token   把用户的id 字符串 和密码 扔进去 ★★★★★
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword()); // id  密码 加密？？？
            userDTO.setToken(token); // 设置token

            String role = one.getRole(); // ROLE_ADMIN  // 获取角色
            // 设置用户的菜单列表
            List<Menu> roleMenus = getRoleMenus(role);  // 获取角色对应的菜单
            userDTO.setMenus(roleMenus); // 设置菜单权限
            // userDTO.setPassword(""); 手动处理一下不给他看密码
            return userDTO;
        } else {
            throw new ServiceException(Constants.CODE_600, "业务异常=>未查询到该用户,用户名或密码错误");
        }
    }

    // 注册
    @Override
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        // 没找到
        if (one == null) {
            one = new User();
            // 复制属性 把userDTO实例  复制给实例one
            BeanUtil.copyProperties(userDTO, one, true);
            // 默认一个普通用户的角色
            one.setRole(RoleEnum.ROLE_STUDENT.toString());
            save(one);  // 把 copy完之后的用户对象存储到数据库
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }

    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }
    }

 /*   @Override
    public Page<User> findPage(Page<User> page, String username, String email, String address) {
        return userMapper.findPage(page, username, email, address);
    }*/

    public Page<Course> searchCourseTableData (Page<Course> page, @Param("id") Integer id){
       return  userMapper.searchCourseTableData(page,id);
    }

  /*  public Page<Course> searchCourseTableDataByStudent(Page<Course>  page,@Param("id") Integer id){
        return  userMapper.searchCourseTableDataByStudent(page,id);
    };*/

    public List<Integer> searchCourseTableDataByStudent( @Param("id") Integer id){
        return  userMapper.searchCourseTableDataByStudent(id);
    };

    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            // LOG.error(e);
             System.out.println("error:"+e);
            throw new ServiceException(Constants.CODE_500, "500 服务器异常，请稍后重试！！！");
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag) {
        // eg:ROLE_ADMIN
        Integer roleId = roleMapper.selectByFlag(roleFlag); // 获取flag 对应的角色id
        // 根据角色id获取的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);
        System.out.println("得到的menuIds："+Arrays.asList(menuIds));
        // 查出系统所有的菜单(树形)
        System.out.println("查询所有菜单");
        List<Menu> menus = menuService.findMenus("");
        for (Menu m:menus) {
            System.out.println("每个menu:"+m.toString());
        }
        // new一个最后筛选完成之后的list
        List<Menu> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Menu menu : menus) { // eg: 角色菜单123456 实际菜单56789  得出菜单56
            if (menuIds.contains(menu.getId())) { // 角色ids 与全部菜单ids 对比
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();

            if (children.size()>0){
                for (Menu m:children) {
                    System.out.println("每个childrenmenu:"+m.toString());
                }
            }
            // removeIf()  移除 children 里面不在 menuIds集合中的 元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }





}

